<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="76px">
        <el-form-item label="处理状态">
          <el-select
            v-model="searchParam.progressStatus"
            placeholder="请选择处理状态"
            clearable
          >
            <el-option
              v-for="item in tabList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="工单状态">
          <el-select
            v-model="searchParam.repairStatus"
            placeholder="请选择工单状态"
            clearable
          >
            <el-option
              v-for="item in useDictionary('EamRepairStatus')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="维修班组">
          <el-select
            v-model="searchParam.repairTeamId"
            placeholder="请输入维修班组"
            clearable
            filterable
          >
            <el-option
              v-for="item in crewList"
              :key="item.id"
              :label="`${item.teamName}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="故障状态">
          <el-select
            style="width: 100%"
            v-model="searchParam.faultStatus"
            placeholder="请选择故障状态"
            clearable
          >
            <el-option
              v-for="item in useDictionary('EamFaultStatus')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="故障来源">
          <el-select
            style="width: 100%"
            v-model="searchParam.repairSource"
            placeholder="请选择故障来源"
            clearable
          >
            <el-option
              v-for="item in useDictionary('EamFaultSource')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <div v-if="isExpanded" style="display: inline">
          <el-form-item label="使用部门">
            <SelectOriganizationDangerGrant
              @change="(ids:string) => getSelectIds(ids)"
              :isCheckStrictly="true"
              :isMultiple="false"
              :disabled="false"
              :data="dataObject('使用部门')"
              :selectData="searchParam.usingDepartmentId"
            />
          </el-form-item>
          <el-form-item label="故障等级">
            <el-select
              style="width: 100%"
              v-model="searchParam.repairLevel"
              placeholder="请选择故障等级"
              clearable
            >
              <el-option
                v-for="item in useDictionary('EamFaultLevel')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="模具信息">
            <el-input
              v-model="searchParam.assetInfo"
              placeholder="请输入模具编号或名称"
              clearable
              @keyup.enter="search"
            />
          </el-form-item>
          <el-form-item label="工单编号">
            <el-input
              v-model="searchParam.repairCode"
              placeholder="请输入工单编号"
              clearable
              @keyup.enter="search"
            />
          </el-form-item>
          <el-form-item label="报修时间">
            <el-date-picker
              v-model="searchParam.reportQuerySearch"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="getReportTime"
            />
          </el-form-item>
          <el-form-item label="维修时间">
            <el-date-picker
              v-model="searchParam.repairQuerySearch"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="getRepairTime"
            />
          </el-form-item>
        </div>
        <el-form-item>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="reset">
            <i-ep-refresh />
            重置
          </el-button>
          <el-button type="primary" @click="toggleSearchArea" link>
            {{ isExpanded ? "收起" : "展开" }}
            <el-icon v-if="isExpanded" class="el-icon--right">
              <i-ep-arrowUp color="#409EFC" />
            </el-icon>
            <el-icon v-else class="el-icon--right">
              <i-ep-arrowDown color="#409EFC" />
            </el-icon>
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          type="primary"
          :disabled="ids.length === 0"
          @click="handleResponse()"
        >
          <i-ep-promotion />
          应答
        </el-button>
        <el-button
          @click="
            useDownload(
              '/andon/andcall/callInformExport',
              '故障维修工单',
              searchParam
            )
          "
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @sort-change="onTableSortChanged"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="维修单编号"
          prop="repairCode"
          min-width="180"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="工单状态"
          prop="repairStatus"
          min-width="120"
          align="center"
        >
          <template #default="scope">
            <el-tag type="warning" v-if="scope.row.repairStatus == 0">
              {{ useDictionary("EamRepairStatus", scope.row.repairStatus) }}
            </el-tag>
            <el-tag
              v-if="
                scope.row.repairStatus * 1 > 0 && scope.row.repairStatus * 1 < 4
              "
            >
              {{ useDictionary("EamRepairStatus", scope.row.repairStatus) }}
            </el-tag>
            <el-tag v-if="scope.row.repairStatus * 1 >= 4" type="info">
              {{ useDictionary("EamRepairStatus", scope.row.repairStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="模具名称"
          prop="assetName"
          min-width="200"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="模具编号"
          prop="assetCode"
          min-width="150"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="故障状态"
          prop="faultStatus"
          min-width="120"
          sortable
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("EamFaultStatus", scope.row.faultStatus) }}
          </template>
        </el-table-column>
        <el-table-column
          label="故障等级"
          prop="repairLevel"
          min-width="120"
          sortable
          align="center"
        >
          <template #default="scope">
            <el-tag
              type="danger"
              v-if="
                scope.row.repairLevel == '1' && scope.row.repairStatus * 1 < 4
              "
            >
              {{ useDictionary("EamFaultLevel", scope.row.repairLevel) }}
            </el-tag>
            <el-tag type="info" v-if="scope.row.repairStatus * 1 >= 4">
              {{ useDictionary("EamFaultLevel", scope.row.repairLevel) }}
            </el-tag>
            <el-tag
              v-if="
                scope.row.repairLevel !== '1' && scope.row.repairStatus * 1 < 4
              "
            >
              {{ useDictionary("EamFaultLevel", scope.row.repairLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="故障描述"
          prop="remarks"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column
          label="使用部门"
          prop="usingDepartmentName"
          min-width="160"
          show-overflow-tooltip
          sortable
          align="center"
        />
        <el-table-column
          label="模具位置"
          prop="locationName"
          min-width="160"
          show-overflow-tooltip
          sortable
          align="center"
        />

        <el-table-column
          label="报修时间"
          prop="repairTime"
          min-width="180"
          show-overflow-tooltip
          sortable
          align="center"
        />
        <el-table-column
          label="报修人"
          prop="repairUserName"
          min-width="100"
          show-overflow-tooltip
          sortable
          align="center"
        />

        <el-table-column
          label="故障来源"
          prop="repairSource"
          min-width="120"
          sortable
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("EamFaultSource", scope.row.repairSource) }}
          </template>
        </el-table-column>
        <el-table-column
          label="是否委外"
          prop="outSourcing"
          min-width="120"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.outSourcing === 1"
              >是</el-tag
            >
            <el-tag type="info" v-else>否</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="维修班组"
          prop="repairTeamName"
          min-width="150"
          show-overflow-tooltip
          sortable
          align="center"
        />
        <el-table-column
          label="维修人"
          prop="repairTeamUserName"
          min-width="100"
          show-overflow-tooltip
          sortable
          align="center"
        />
        <el-table-column
          label="维修开始时间"
          prop="repairStartTime"
          min-width="160"
          show-overflow-tooltip
          sortable
          align="center"
        />
        <el-table-column
          label="维修结束时间"
          prop="repairEndTime"
          min-width="160"
          show-overflow-tooltip
          sortable
          align="center"
        />
        <el-table-column
          label="维修情况说明"
          prop="repairSituation"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column fixed="right" label="操作" width="170" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
            >
              <i-ep-search />
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              :disabled="scope.row.repairStatus == 0"
              @click="openDialog(scope.row)"
            >
              <i-ep-edit />
              维修
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <mold-eam-repair-handle-me-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :assetKind="assetKind"
      :userType="userType"
      @reset-table="(id:string) => (id?.length ? getTableList() : search())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { getCrewListApi } from "@/utils/commonData";
import { filterOrder } from "@/utils/commonHooks";
defineOptions({
  name: "EAMEQUEAMREPAIRHANDLELIST",
  inheritAttrs: false,
});

const tabList = [
  { name: "所有", id: 0 },
  { name: "待处理", id: 1 },
  { name: "处理中", id: 2 },
  { name: "已完成", id: 3 },
];

const props = defineProps({
  assetKind: {
    type: Number,
    default: null,
  },
  // 1 组长（看所有的）   2 普通员工（看自己的和未应答的）
  userType: {
    type: String,
    default: "",
  },
});

const { assetKind, userType } = toRefs(props);

// 请求参数
const requestApi =
  userType.value === "1"
    ? "/eam/mouldrepairorder/queryByPage"
    : "/eam/mouldrepairorder/queryMyRepairOrder";

// 是否需要分页
const pagination = true;

const initParam = reactive({
  sort: {
    column: "",
    orderBy: "",
  },
});

// 初始化搜索参数数据
const searchParamInit = {
  repairStatus: "",
  repairUser: "",
  faultStatus: "",
  repairLevel: "",
  repairSource: "",
  assetCode: "",
  assetInfo: "",
  repairCode: "",
  reportQuerySearch: [],
  reportQueryStartTime: "",
  reportQueryEndTime: "",
  repairQuerySearch: [],
  repairQueryStartTime: "",
  repairQueryEndTime: "",
  assetKind: assetKind.value,
};

const deleteParam = {
  api: "/eam/mouldrepairorder/delete",
  data: { assetKind: assetKind.value },
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

// 排序
// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  console.log(prop, order);

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}
// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });

onMounted(() => {
  getTableList();
});

const dataTableRef = ref();
const ids = ref<any>([]);
const idsObj = ref<any>([]);
// 只选中一条数据
const handleSelectionChange = (list: any) => {
  ids.value = [];
  if (list.length > 1) {
    dataTableRef.value.clearSelection();
    dataTableRef.value.toggleRowSelection(list[list.length - 1]);
  }
  idsObj.value = [list[list.length - 1]];
  ids.value = [list[list.length - 1]?.id];
};

// 切换搜索折叠
const isExpanded = ref(false);
function toggleSearchArea() {
  isExpanded.value = !isExpanded.value;
}

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

/** 打开维修单表单弹窗 */
function openDialog(roleObj?: any) {
  if (roleObj) {
    addDialog.title = "修改维修单";
    addDialog.data = {
      id: roleObj.id,
    };
    addDialog.visible = true;
  } else {
    addDialog.title = "新增维修单";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开维修单表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "维修单详情";
  addDialog.data = {
    id: roleObj.id,
  };
  addDialog.visible = true;
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getRepairTime(data: any) {
  if (data) {
    searchParam.value.repairQueryStartTime = data[0];
    searchParam.value.repairQueryEndTime = data[1];
  } else {
    searchParam.value.repairQueryStartTime = "";
    searchParam.value.repairQueryEndTime = "";
  }
}

function getReportTime(data: any) {
  if (data) {
    searchParam.value.reportQueryStartTime = data[0];
    searchParam.value.reportQueryEndTime = data[1];
  } else {
    searchParam.value.reportQueryStartTime = "";
    searchParam.value.reportQueryEndTime = "";
  }
}

/** 选择组织机构并赋值id  start **/
function getSelectIds(ids: [] | string) {
  if (ids) {
    searchParam.value.usingDepartmentId = ids;
  } else {
    searchParam.value.usingDepartmentId = "";
  }
}

/**
 * 应答
 */
const handleResponse = () => {
  ElMessageBox.confirm("确认是否应答已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    if (idsObj.value[0].repairStatus != "0") {
      ElMessage.error("请选择未响应的维修单");
      return;
    } else {
      await request({
        url: "/eam/mouldrepairorder/updateStatus",
        method: "post",
        data: {
          id: ids.value[0],
          repairStatus: 1,
        },
      })
        .then(() => {
          ElMessage.success("应答成功");
          getTableList();
        })
        .finally(() => {});
    }
  });
};

//班组
const crewList = ref(<any>[]);
async function getCrews() {
  crewList.value = (await getCrewListApi({ teamType: "1" })) || [];
}

// 使用部门选择
const dataObject = (item: string) => {
  return {
    name: item,
    defaultProps: {
      children: "nodes",
      label: "organizationName",
      value: "id",
    },
    api: "/system/sysOrganization/getUsableTree",
  };
};
onMounted(() => {
  getCrews();
});
</script>
